<?php

namespace App\Http\Controllers\admin;

use App\ArticleModel;
use App\Http\Controllers\Controller;
use App\TypeModel;
use Illuminate\Http\Request;

class ArticleController extends Controller
{
    public function articleinsert(Request $request)
    {
        $id=$request->input("id");
        $Article=ArticleModel::find($id);
       $input = $request->input();
       $cover = $request->file("cover");
        $cover_name = "ar_cover" . date("Ymd_His") . rand(1, 1000) . "." . $cover->getClientOriginalExtension();
        $cover->move(public_path('ar_cover'), $cover_name);
        $input['cover'] = "ar_cover/" . $cover_name;
        if ($id==0){
            $ok = ArticleModel::create($input);
            if ($ok) {
                return $this->success(null, [
                    "title" => "操作成功",
                    "text" => "数据添加成功",
                ]);
            }
        }else{
            $ok = $Article->update($input);
            if ($ok) {
                return $this->success(null, [
                    "title" => "操作成功",
                    "text" => "数据修改成功",
                ]);
            }
        }
    }

    public function articlepage(Request $request)
    {
        $types=TypeModel::get();
        return view('admin.addarticle',compact("types"));
    }


    public function articles(Request $request)
    {
        $articles=ArticleModel::get();
        return view('admin.articles',compact("articles"));
    }

    public function updatearticle(Request $request)
    {
        $id=$request->input("id");
        $types=TypeModel::get();
       $article=ArticleModel::find($id);
       return view("admin.addarticle",compact("article","types"));
    }


    public function ar_file(Request $request)
    {
        $img = $request->file('article_file');

        if ($img->isValid()) {

            $ext = $img->getClientOriginalExtension();
            $size = $img->getSize();

            $img_ext = ['jpg', 'png', 'gif', 'jpeg'];
            $img_size = 1024 * 1024 * 2;

            if (!in_array($ext, $img_ext)) {
                return ['msg' => '图片格式不对，请重新选择合法的图片格式', 'status', 'false'];
            } elseif ($size > $img_size) {
                return ['msg' => '图片太大了！', 'status', 'false'];
            }

            $img_path = 'upload/article/';
            $img_name = time() . '.' . $ext;

            $save = $img->move($img_path, $img_name);
            if ($save) {
                $url =asset("/") . $img_path . $img_name;
                return ["errno" => 0, "data" => [$url]];
            }
            return ['msg' => 'رەسىم چىقىرىش مەغلۇپ بولدى', 'status', 'false'];
        }
    }
}
